import ContextPadProvider from 'bpmn-js/lib/features/context-pad/ContextPadProvider'
import { assign } from 'min-dash'

type Injector = import('didi').Injector
type EventBus = import('diagram-js/lib/core/EventBus').default
type ContextPad = import('diagram-js/lib/features/context-pad/ContextPad').default
type Modeling = import('bpmn-js/lib/features/modeling/Modeling').default
type ElementFactory = import('bpmn-js/lib/features/modeling/ElementFactory').default
type AppendPreview = import('bpmn-js/lib/features/append-preview/AppendPreview').default
type Connect = import('diagram-js/lib/features/connect/Connect').default
type Create = import('diagram-js/lib/features/create/Create').default
type PopupMenu = import('diagram-js/lib/features/popup-menu/PopupMenu').default
type Rules = import('diagram-js/lib/features/rules/Rules').default
export type Translate = typeof import('diagram-js/lib/i18n/translate/translate').default
type Element = import('bpmn-js/lib/model/Types').Element
type Shape = import('bpmn-js/lib/model/Types').Shape

class EnhancementContextPadProvider extends ContextPadProvider {
  private _modeling: Modeling
  private _elementFactory: ElementFactory
  private _autoPlace: any
  private _create: Create
  private _canvas: any
  private _appendPreview: AppendPreview
  private _eventBus: EventBus
  
  constructor(
    config: any,
    injector: Injector,
    eventBus: EventBus,
    contextPad: ContextPad,
    modeling: Modeling,
    elementFactory: ElementFactory,
    connect: Connect,
    create: Create,
    popupMenu: PopupMenu,
    canvas: any,
    rules: Rules,
    translate: Translate,
    appendPreview: AppendPreview,
  ) {
    super(
      config,
      injector,
      eventBus,
      contextPad,
      modeling,
      elementFactory,
      connect,
      create,
      popupMenu,
      canvas,
      rules,
      translate,
      appendPreview,
    )

    this._modeling = modeling
    this._elementFactory = elementFactory
    this._create = create
    this._canvas = canvas
    this._appendPreview = appendPreview
    this._eventBus = eventBus

    this._autoPlace = injector.get('autoPlace', false)
    
    // 监听元素创建事件，为新创建的用户任务设置默认属性
    this.setupEventListeners()
  }
  
  /**
   * 设置事件监听器，用于在创建元素时添加默认属性
   */
  private setupEventListeners() {
    // 监听元素添加事件
    this._eventBus.on('shape.added', (event: any) => {
      const { element } = event
      
      // 如果是新创建的用户任务，设置默认属性
      if (element.type === 'bpmn:UserTask' && element.businessObject) {
        // 使用setTimeout确保元素已经完全添加到画布
        setTimeout(() => {
          this.setUserTaskDefaults(element)
        }, 0)
      }
    })
    
    // 监听元素创建事件（用于拖拽创建）
    this._eventBus.on('create.end', (event: any) => {
      const { shape } = event
      
      if (shape && shape.type === 'bpmn:UserTask' && shape.businessObject) {
        setTimeout(() => {
          this.setUserTaskDefaults(shape)
        }, 0)
      }
    })
  }
  
  /**
   * 为用户任务设置默认属性
   */
  private setUserTaskDefaults(element: Shape) {
    try {
      const businessObject = element.businessObject
      const updates: any = {}
      
      // 如果还没有名称，设置默认名称
      if (!businessObject.name) {
        updates.name = this.generateDefaultTaskName()
      }

      // 添加默认审批模式
      updates['flowable:approvalMode'] = 'assignee'
      
      // 审批人为空时属性默认为自动同意
      updates['flowable:emptyAssigneeStrategy'] = 'autoApprove'
      
      // 如果有属性需要更新，执行更新
      if (Object.keys(updates).length > 0) {
        this._modeling.updateProperties(element, updates)
        console.log(`为用户任务 ${element.id} 设置默认属性:`, updates)
      }
      
    } catch (error) {
      console.error('设置用户任务默认属性失败:', error)
    }
  }
  
  /**
   * 生成默认的任务名称
   */
  private generateDefaultTaskName(): string {
    try {
      // 获取当前画布上所有的用户任务数量
      const elementRegistry = this._canvas.getRootElement().children || []
      const userTaskCount = elementRegistry.filter((el: any) => 
        el.type === 'bpmn:UserTask'
      ).length
      
      return `用户任务${userTaskCount-1}`
    } catch (error) {
      console.error('生成默认任务名称失败:', error)
      return '新用户任务'
    }
  }

  getContextPadEntries(element: Element) {
    console.log('getContextPadEntries', element)
    const elementFactory = this._elementFactory,
      create = this._create,
      autoPlace = this._autoPlace,
      appendPreview = this._appendPreview
    const actions: Record<string, any> = {}

    function appendUserTask(event: Event, element: Shape) {
      const shape = elementFactory.createShape(assign({ type: 'bpmn:UserTask' }))
      create.start(event, shape, {
        source: element,
      })
    }

    const append = autoPlace
      ? function (_event: any, element: Shape) {
          const shape = elementFactory.createShape(assign({ type: 'bpmn:UserTask' }))
          const newElement = autoPlace.append(element, shape)
          
          // 注意：这里不需要手动设置默认属性，因为事件监听器会自动处理
          // setupEventListeners() 中的 'shape.added' 事件会自动触发
          
          return newElement
        }
      : appendUserTask

    const previewAppend = autoPlace
      ? function (_event: any, element: Shape) {
          // mouseover
          appendPreview.create(element, 'bpmn:UserTask', {})
          return () => {
            // mouseout
            appendPreview.cleanUp()
          }
        }
      : null
      
    // 添加创建用户任务按钮
    actions['append.append-task'] = {
      group: 'model',
      className: 'bpmn-icon-user-task',
      title: '用户任务',
      action: {
        dragstart: appendUserTask,
        click: append,
        hover: previewAppend,
      },
    }
    
    return actions
  }
}

export default EnhancementContextPadProvider
